package com.alibaba.citrus.ots.application.report.ability.facade.service;

import com.alibaba.citrus.ots.application.report.ability.utils.DomUtil;
import com.alibaba.citrus.ots.common.annotation.FacadeInvoker;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.alibaba.lattice2.epoch.sdk.model.annotation.EpochAPI;
import com.epoch.app.bcorder.model.dto.EmployeeGetCurrentLoginResponse;
import com.epoch.app.bcorder.service.BcOrderService;
import com.epoch.app.crplatformenhance.enums.InventoryAllotTypeEnum;
import com.epoch.app.crplatformenhance.model.dto.GetTopOrganizationListRequest;
import com.epoch.app.crplatformenhance.model.dto.InventoryAllotDetailDTO;
import com.epoch.app.crplatformenhance.model.dto.PageQueryAlloctDetailsRequest;
import com.epoch.app.crplatformenhance.model.dto.TopOrganizationListResponse;
import com.epoch.app.crplatformenhance.service.CrPlatformEnhanceService;
import com.epoch.app.otsapplicationreportsdk.contants.OtsApplicationReportSdkConstants;
import com.epoch.app.otsapplicationreportsdk.ecinventorydetail.dto.PageLinkDetailRequest;
import com.epoch.app.otsapplicationreportsdk.ecinventorydetail.dto.PageQueryDetailRequest;
import com.epoch.app.otsapplicationreportsdk.ecinventorydetail.model.EcInventoryDetail;
import com.epoch.app.otsapplicationreportsdk.ecinventorydetail.service.EcInventoryDetailService;
import com.epoch.app.otsapplicationreportsdk.inventoryreport.dto.CommonInventoryReportRequest;
import com.epoch.app.otsapplicationreportsdk.inventoryreport.dto.EcInventoryReportRequest;
import com.epoch.app.otsapplicationreportsdk.inventoryreport.dto.EcLinkInventoryReportRequest;
import com.epoch.app.otsapplicationreportsdk.inventoryreport.dto.EverydayInventoryReportRequest;
import com.epoch.app.otsapplicationreportsdk.inventoryreport.dto.WarehouseInventoryReportRequest;
import com.epoch.app.otsapplicationreportsdk.inventoryreport.service.InventoryReportService;
import com.epoch.app.otsapplicationreportsdk.model.dto.EcInventoryVO;
import com.epoch.app.otsapplicationreportsdk.model.dto.EcLinkInventoryVO;
import com.epoch.app.otsapplicationreportsdk.model.dto.InventoryDetailDTO;
import com.epoch.app.otsapplicationreportsdk.model.dto.QuerySpecWarehouseIdForReportResponse;
import com.epoch.app.otsapplicationreportsdk.model.dto.WareInventoryVO;
import com.epoch.app.otsapplicationreportsdk.service.OtsApplicationReportSdkService;
import com.epoch.app.otsapplicationreportsdk.warehouseinventorydetail.dto.ListAvailableRequest;
import com.epoch.app.otsapplicationreportsdk.warehouseinventorydetail.dto.LoadListRequest;
import com.epoch.app.otsapplicationreportsdk.warehouseinventorydetail.dto.StatByCategoryDimRequest;
import com.epoch.app.otsapplicationreportsdk.warehouseinventorydetail.model.WarehouseInventoryDetail;
import com.epoch.app.otsapplicationreportsdk.warehouseinventorydetail.service.WarehouseInventoryDetailService;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class InventoryReportServiceImpl implements InventoryReportService {

    private static Log log = Log.getLogger(InventoryReportServiceImpl.class);

    @Autowired
    private WarehouseInventoryDetailService warehouseInventoryDetailService;

    @Autowired
    private EcInventoryDetailService ecInventoryDetailService;

    @Autowired
    private CrPlatformEnhanceService otsPlatformEnhanceService;

    @Autowired
    private OtsApplicationReportSdkService otsApplicationReportSdkService;

    @Autowired
    private BcOrderService bcOtsService;

    private final static String BRANCH_COMPANY_ORG_CODE = "103";

    /**
     * 仓库库存报表统计
     */
    @EpochAPI(api = "InventoryReport$warehouseInventoryReport")
    @Override
    public Result<List<WareInventoryVO>> warehouseInventoryReport(WarehouseInventoryReportRequest warehouseInventoryReportRequest) {
        Integer dimCode = warehouseInventoryReportRequest.getDimCode();
        if (dimCode != null && dimCode == 2) {
            //类目维度统计
            StatByCategoryDimRequest request = new StatByCategoryDimRequest();
            request.setStatisticalDate(DomUtil.getToday());
            if (StringUtils.isNotBlank(warehouseInventoryReportRequest.getWarehouseAreaId())) {
                request.setWarehouseAreaId(warehouseInventoryReportRequest.getWarehouseAreaId());
            }
            String bizUnitId = findBizUnitId();
            if (bizUnitId != null) {
                request.setBizUnitId(bizUnitId);
            }
            request.setRootCategoryIdList(warehouseInventoryReportRequest.getRootCategoryIdList());
            request.setRootCategoryId(warehouseInventoryReportRequest.getRootCategoryId());
            request.setGoodsIdList(warehouseInventoryReportRequest.getGoodsIdList());
            request.setOuterItemId(warehouseInventoryReportRequest.getOuterItemId());
            request.setStart(warehouseInventoryReportRequest.getStart());
            request.setLimit(warehouseInventoryReportRequest.getLimit());
            //add by myw,for 20220622 产品需求
            //1.需排除6140销售组织的逻辑仓库库存数据
            //2.需排除类型是工厂仓的库存数据
            //3.需排除类型是销售单元仓，且销售组织=1171的库存数据
            request.setExcludeOrgs(Lists.newArrayList(OtsApplicationReportSdkConstants.NYK_SALE_ORG_ID()));
            QuerySpecWarehouseIdForReportResponse querySpecWarehouseIdForReportResponse = otsApplicationReportSdkService
                .querySpecWarehouseIdForReport();
            if (Objects.nonNull(querySpecWarehouseIdForReportResponse)
                && org.apache.commons.collections4.CollectionUtils.isNotEmpty(
                querySpecWarehouseIdForReportResponse.getResult())) {
                request.setExcludeWarehouseIds(querySpecWarehouseIdForReportResponse.getResult());
            }
            Result<List<WarehouseInventoryDetail>> result = warehouseInventoryDetailService.statByCategoryDim(request);
            if (result == null || CollectionUtils.isEmpty(result.getResult())) {
                return Result.listEmptySuccess();
            }
            if (warehouseInventoryReportRequest.getIsExcel()) {
                return convert2ExcelVO(result);
            }
            return convert2VO(result);
        }
        //货品维度统计
        ListAvailableRequest request = new ListAvailableRequest();
        request.setStatisticalDate(DomUtil.getToday());
        if (StringUtils.isNotBlank(warehouseInventoryReportRequest.getWarehouseAreaId())) {
            request.setWarehouseAreaId(warehouseInventoryReportRequest.getWarehouseAreaId());
        }
        String bizUnitId = findBizUnitId();
        if (bizUnitId != null) {
            request.setBizUnitId(bizUnitId);
        }
        request.setRootCategoryIdList(warehouseInventoryReportRequest.getRootCategoryIdList());
        request.setRootCategoryId(warehouseInventoryReportRequest.getRootCategoryId());
        request.setGoodsIdList(warehouseInventoryReportRequest.getGoodsIdList());
        request.setOuterItemId(warehouseInventoryReportRequest.getOuterItemId());
        request.setStart(warehouseInventoryReportRequest.getStart());
        request.setLimit(warehouseInventoryReportRequest.getLimit());
        //add by myw,for 20220622 产品需求
        //1.需排除6140销售组织的逻辑仓库库存数据
        //2.需排除类型是工厂仓的库存数据
        //3.需排除类型是销售单元仓，且销售组织=1171的库存数据
        request.setExcludeOrgs(Lists.newArrayList(OtsApplicationReportSdkConstants.NYK_SALE_ORG_ID()));
        QuerySpecWarehouseIdForReportResponse querySpecWarehouseIdForReportResponse = otsApplicationReportSdkService
            .querySpecWarehouseIdForReport();
        if (Objects.nonNull(querySpecWarehouseIdForReportResponse) && org.apache.commons.collections4.CollectionUtils
            .isNotEmpty(querySpecWarehouseIdForReportResponse.getResult())) {
            request.setExcludeWarehouseIds(querySpecWarehouseIdForReportResponse.getResult());
        }
        Result<List<WarehouseInventoryDetail>> result = warehouseInventoryDetailService.listAvailable(request);
        if (result == null || CollectionUtils.isEmpty(result.getResult())) {
            return Result.listEmptySuccess();
        }
        if (warehouseInventoryReportRequest.getIsExcel()) {
            return convert2ExcelVO(result);
        }
        return convert2VO(result);
    }

    //数值转化为千分号
    private Result<List<WareInventoryVO>> convert2VO(Result<List<WarehouseInventoryDetail>> result) {
        List<WareInventoryVO> wareInventoryVOS = new ArrayList<>();
        result.getResult().stream().forEach(x -> {
            WareInventoryVO vo = new WareInventoryVO();
            vo.setWarehouseAreaName(x.getWarehouseAreaName());
            vo.setGoodsId(x.getGoodsId());
            vo.setOuterItemId(x.getOuterItemId());
            vo.setGoodsName(x.getGoodsName());
            vo.setCategoryId(StringUtils.isBlank(x.getCategoryId()) ? x.getRootCategoryId() : x.getCategoryId());
            vo.setCategoryName(
                StringUtils.isBlank(x.getCategoryName()) ? x.getRootCategoryName() : x.getCategoryName());
            vo.setTotalQuantity(DomUtil.thousandthFormat(x.getTotalQuantity()));
            vo.setAvailableQuantity(DomUtil.thousandthFormat(x.getAvailableQuantity()));
            vo.setInspectQuantity(DomUtil.thousandthFormat(x.getInspectQuantity()));
            vo.setWithholdingQuantity(DomUtil.thousandthFormat(x.getWithholdingQuantity()));
            vo.setOnwayQuantity(DomUtil.thousandthFormat(x.getOnwayQuantity()));
            vo.setExceedThreeMonthsQuantity(DomUtil.thousandthFormat(x.getExceedThreeMonthsQuantity()));
            vo.setEarlyTwoMonthsQuantity(DomUtil.thousandthFormat(x.getEarlyTwoMonthsQuantity()));
            vo.setMidTwoMonthsQuantity(DomUtil.thousandthFormat(x.getMidTwoMonthsQuantity()));
            vo.setLateTwoMonthsQuantity(DomUtil.thousandthFormat(x.getLateTwoMonthsQuantity()));
            vo.setEarlyOneMonthQuantity(DomUtil.thousandthFormat(x.getEarlyOneMonthQuantity()));
            vo.setMidOneMonthQuantity(DomUtil.thousandthFormat(x.getMidOneMonthQuantity()));
            vo.setLateOneMonthQuantity(DomUtil.thousandthFormat(x.getLateOneMonthQuantity()));
            vo.setEarlyThisMonthQuantity(DomUtil.thousandthFormat(x.getEarlyThisMonthQuantity()));
            vo.setMidThisMonthQuantity(DomUtil.thousandthFormat(x.getMidThisMonthQuantity()));
            vo.setLateThisMonthQuantity(DomUtil.thousandthFormat(x.getLateThisMonthQuantity()));
            vo.setFrozenQuantity(DomUtil.thousandthFormat(x.getFrozenQuantity()));
            vo.setUsableQuantity(DomUtil.thousandthFormat(x.getUsableQuantity()));
            if ("1".equals(x.getSpecTag())) {
                vo.setFourthExpiredQuantity("_");
                vo.setThirdExpiredQuantity("_");
                vo.setApproachExpiredQuantity("_");
                vo.setNormalQuantity("_");
                vo.setFourthExpiredTotal("_");
                vo.setThirdExpiredTotal("_");
                vo.setApproachExpiredTotal("_");
                vo.setNormalTotal("_");
            } else {
                vo.setFourthExpiredQuantity(DomUtil.thousandthFormat(x.getFourthExpiredQuantity()));
                vo.setThirdExpiredQuantity(DomUtil.thousandthFormat(x.getThirdExpiredQuantity()));
                vo.setApproachExpiredQuantity(DomUtil.thousandthFormat(x.getApproachExpiredQuantity()));
                vo.setNormalQuantity(DomUtil.thousandthFormat(x.getNormalQuantity()));
                vo.setFourthExpiredTotal(DomUtil.thousandthFormat(x.getFourthExpiredTotal()));
                vo.setThirdExpiredTotal(DomUtil.thousandthFormat(x.getThirdExpiredTotal()));
                vo.setApproachExpiredTotal(DomUtil.thousandthFormat(x.getApproachExpiredTotal()));
                vo.setNormalTotal(DomUtil.thousandthFormat(x.getNormalTotal()));
            }
            wareInventoryVOS.add(vo);
        });
        return Result.listSuccess(wareInventoryVOS, result.getTotal());
    }

    //数值转化为字符串
    private Result<List<WareInventoryVO>> convert2ExcelVO(Result<List<WarehouseInventoryDetail>> result) {
        List<WareInventoryVO> wareInventoryVOS = new ArrayList<>();
        result.getResult().stream().forEach(x -> {
            WareInventoryVO vo = new WareInventoryVO();
            vo.setWarehouseAreaName(x.getWarehouseAreaName());
            vo.setGoodsId(x.getGoodsId());
            vo.setOuterItemId(x.getOuterItemId());
            vo.setGoodsName(x.getGoodsName());
            vo.setCategoryId(StringUtils.isBlank(x.getCategoryId()) ? x.getRootCategoryId() : x.getCategoryId());
            vo.setCategoryName(
                StringUtils.isBlank(x.getCategoryName()) ? x.getRootCategoryName() : x.getCategoryName());
            vo.setTotalQuantity(DomUtil.stringFormat(x.getTotalQuantity()));
            vo.setAvailableQuantity(DomUtil.stringFormat(x.getAvailableQuantity()));
            vo.setInspectQuantity(DomUtil.stringFormat(x.getInspectQuantity()));
            vo.setWithholdingQuantity(DomUtil.stringFormat(x.getWithholdingQuantity()));
            vo.setOnwayQuantity(DomUtil.stringFormat(x.getOnwayQuantity()));
            vo.setExceedThreeMonthsQuantity(DomUtil.stringFormat(x.getExceedThreeMonthsQuantity()));
            vo.setEarlyTwoMonthsQuantity(DomUtil.stringFormat(x.getEarlyTwoMonthsQuantity()));
            vo.setMidTwoMonthsQuantity(DomUtil.stringFormat(x.getMidTwoMonthsQuantity()));
            vo.setLateTwoMonthsQuantity(DomUtil.stringFormat(x.getLateTwoMonthsQuantity()));
            vo.setEarlyOneMonthQuantity(DomUtil.stringFormat(x.getEarlyOneMonthQuantity()));
            vo.setMidOneMonthQuantity(DomUtil.stringFormat(x.getMidOneMonthQuantity()));
            vo.setLateOneMonthQuantity(DomUtil.stringFormat(x.getLateOneMonthQuantity()));
            vo.setEarlyThisMonthQuantity(DomUtil.stringFormat(x.getEarlyThisMonthQuantity()));
            vo.setMidThisMonthQuantity(DomUtil.stringFormat(x.getMidThisMonthQuantity()));
            vo.setLateThisMonthQuantity(DomUtil.stringFormat(x.getLateThisMonthQuantity()));
            vo.setFrozenQuantity(DomUtil.stringFormat(x.getFrozenQuantity()));
            vo.setUsableQuantity(DomUtil.stringFormat(x.getUsableQuantity()));
            if ("1".equals(x.getSpecTag())) {
                vo.setFourthExpiredQuantity(null);
                vo.setThirdExpiredQuantity(null);
                vo.setApproachExpiredQuantity(null);
                vo.setNormalQuantity(null);
                vo.setFourthExpiredTotal(null);
                vo.setThirdExpiredTotal(null);
                vo.setApproachExpiredTotal(null);
                vo.setNormalTotal(null);
            } else {
                vo.setFourthExpiredQuantity(DomUtil.stringFormat(x.getFourthExpiredQuantity()));
                vo.setThirdExpiredQuantity(DomUtil.stringFormat(x.getThirdExpiredQuantity()));
                vo.setApproachExpiredQuantity(DomUtil.stringFormat(x.getApproachExpiredQuantity()));
                vo.setNormalQuantity(DomUtil.stringFormat(x.getNormalQuantity()));
                vo.setFourthExpiredTotal(DomUtil.stringFormat(x.getFourthExpiredTotal()));
                vo.setThirdExpiredTotal(DomUtil.stringFormat(x.getThirdExpiredTotal()));
                vo.setApproachExpiredTotal(DomUtil.stringFormat(x.getApproachExpiredTotal()));
                vo.setNormalTotal(DomUtil.stringFormat(x.getNormalTotal()));
            }
            wareInventoryVOS.add(vo);
        });
        return Result.listSuccess(wareInventoryVOS, result.getTotal());
    }

    @EpochAPI(api = "InventoryReport$everydayInventoryReport")
    @Override
    public Result<List<InventoryDetailDTO>> everydayInventoryReport(EverydayInventoryReportRequest everydayInventoryReportRequest) {
        log.info("everydayInventoryReport_request={}", JSON.toJSONString(everydayInventoryReportRequest));
        PageQueryAlloctDetailsRequest request = new PageQueryAlloctDetailsRequest();
        request.setDistributionType(everydayInventoryReportRequest.getDistributionType());
        request.setOrganizationCode(everydayInventoryReportRequest.getOrganizationCode());
        if(StringUtils.isNotBlank(everydayInventoryReportRequest.getCreator())){
            request.setDimensionId(Lists.newArrayList(everydayInventoryReportRequest.getCreator()));
        }
        EmployeeGetCurrentLoginResponse employeeGetCurrentLoginResponse = bcOtsService.employeeGetCurrentLogin();
        if (employeeGetCurrentLoginResponse == null) {
            return Result.fail("-1", "取用户登录信息失败");
        }
        //不控制业务员数据权限，有组织权限控制即可
        //        if (employeeGetCurrentLoginResponse.getIsSales()){
        //            request.setDimensionId(Arrays.asList(employeeGetCurrentLoginResponse.getEmployeeId()));
        //        }
        request.setScItemId(everydayInventoryReportRequest.getScItemId());
        request.setStart(everydayInventoryReportRequest.getStart());
        request.setLimit(everydayInventoryReportRequest.getLimit());
        log.info("pageQueryAlloctDetails_request={}", JSON.toJSONString(request));
        Result<List<InventoryAllotDetailDTO>> result = otsPlatformEnhanceService.pageQueryAlloctDetails(request);
        log.info("pageQueryAlloctDetails_result={}", JSON.toJSONString(result));
        List<InventoryDetailDTO> list = result.getResult().stream().map(x -> {
            InventoryDetailDTO dto = new InventoryDetailDTO();
            BeanUtils.copyProperties(x, dto);
            dto.setDistributionType(InventoryAllotTypeEnum.of(dto.getDistributionType()).getDesc());
            if (org.apache.commons.lang3.StringUtils.isNotEmpty(dto.getFeature())) {
                Map<String, String> map = JSONObject.parseObject(dto.getFeature(),
                    new TypeReference<Map<String, String>>() {});
                dto.setScItemId(map.get("sc_item_outer_id"));
                dto.setDimensionId(map.get("dimension_out_id"));
            }
            if (StringUtils.isNotBlank(dto.getInventoryAllotTime()) && dto.getInventoryAllotTime().length() >= 10) {
                dto.setInventoryAllotTime(dto.getInventoryAllotTime().substring(0, 10));
            }
            if (StringUtils.isNotBlank(dto.getRemainingQuantity())) {
                dto.setRemainingQuantity(String.valueOf(Double.valueOf(dto.getRemainingQuantity()).intValue()));
            }
            if (StringUtils.isNotBlank(dto.getUsedQuantity())) {
                dto.setUsedQuantity(String.valueOf(Double.valueOf(dto.getUsedQuantity()).intValue()));
            }
            return dto;
        }).collect(Collectors.toList());
        return Result.listSuccess(list, list.size());
    }

    @EpochAPI(api = "InventoryReport$commonInventoryReport")
    @Override
    public Result<List<WareInventoryVO>> commonInventoryReport(CommonInventoryReportRequest commonInventoryReportRequest) {
        LoadListRequest request = new LoadListRequest();
        request.setStatisticalDate(DomUtil.getToday());
        request.setOuterItemId(commonInventoryReportRequest.getOuterItemId());
        request.setGoodsIdList(commonInventoryReportRequest.getGoodsIdList());
        //权限控制范围内仓库存数据查询
        if (StringUtils.isNotBlank(commonInventoryReportRequest.getWarehouseAreaId())) {
            request.setWarehouseAreaId(commonInventoryReportRequest.getWarehouseAreaId());
        }
        String bizUnitId = findBizUnitId();
        if (bizUnitId != null) {
            request.setBizUnitId(bizUnitId);
        }
        request.setStart(commonInventoryReportRequest.getStart());
        request.setLimit(commonInventoryReportRequest.getLimit());
        //add by myw,for 20220622 产品需求
        //1.需排除6140销售组织的逻辑仓库库存数据
        //2.需排除类型是工厂仓的库存数据
        //3.需排除类型是销售单元仓，且销售组织=1171的库存数据
        request.setExcludeOrgs(Lists.newArrayList(OtsApplicationReportSdkConstants.NYK_SALE_ORG_ID()));
        QuerySpecWarehouseIdForReportResponse querySpecWarehouseIdForReportResponse = otsApplicationReportSdkService
            .querySpecWarehouseIdForReport();
        if (Objects.nonNull(querySpecWarehouseIdForReportResponse) && org.apache.commons.collections4.CollectionUtils
            .isNotEmpty(querySpecWarehouseIdForReportResponse.getResult())) {
            request.setExcludeWarehouseIds(querySpecWarehouseIdForReportResponse.getResult());
        }
        log.info("commonInventoryReport_loadList_request={}", JSON.toJSONString(request));
        Result<List<WarehouseInventoryDetail>> result = warehouseInventoryDetailService.loadList(request);
        //log.info("commonInventoryReport_loadList_result={}", JSON.toJSONString(result));
        if (result == null || CollectionUtils.isEmpty(result.getResult())) {
            return Result.listEmptySuccess();
        }
        if (commonInventoryReportRequest.getIsExcel()) {
            return convert2ExcelVO(result);
        }
        return convert2VO(result);
    }

    @EpochAPI(api = "InventoryReport$ecInventoryReport")
    @Override
    public Result<List<EcInventoryVO>> ecInventoryReport(EcInventoryReportRequest ecInventoryReportRequest) {
        log.info("ecInventoryReport_request={}", JSON.toJSONString(ecInventoryReportRequest));
        PageQueryDetailRequest request = new PageQueryDetailRequest();
        request.setDepartmentCodes(ecInventoryReportRequest.getDepartmentCodes());
        request.setPlatformCodes(ecInventoryReportRequest.getPlatformCodes());
        request.setSapFactoryCode(ecInventoryReportRequest.getSapFactoryCode());
        request.setWarehouseCode(ecInventoryReportRequest.getWarehouseCode());
        request.setCode(ecInventoryReportRequest.getCode());
        request.setWarehouseIdList(ecInventoryReportRequest.getWarehouseIdList());
        request.setGoodsIdList(ecInventoryReportRequest.getGoodsIdList());
        request.setOuterItemIdList(ecInventoryReportRequest.getOuterItemIdList());
        request.setStart(ecInventoryReportRequest.getStart());
        request.setLimit(ecInventoryReportRequest.getLimit());
        request.setOuterItemId(ecInventoryReportRequest.getOuterItemId());
        //默认按照超期降序
        if (StringUtils.isBlank(ecInventoryReportRequest.getDir())) {
            request.setDir("thirdExpiredQuantity");
            request.setAsc(false);
        } else {
            request.setDir(ecInventoryReportRequest.getDir());
            request.setAsc(ecInventoryReportRequest.getAsc());
        }
        request.setStatisticalDate(DomUtil.getToday());
        log.info("pageQueryDetail_request={}", JSON.toJSONString(request));
        Result<List<EcInventoryDetail>> result = ecInventoryDetailService.pageQueryDetail(request);
        //log.info("pageQueryDetail_result={}", JSON.toJSONString(result));
        if (result == null || CollectionUtils.isEmpty(result.getResult())) {
            return Result.listEmptySuccess();
        }
        boolean isExcel = ecInventoryReportRequest.getIsExcel();
        List<EcInventoryVO> ecInventoryVOS = new ArrayList<>();
        result.getResult().stream().forEach(x -> {
            EcInventoryVO vo = new EcInventoryVO();
            vo.setDepartmentName(x.getDepartmentName());
            vo.setPlatformName(x.getPlatformName());
            vo.setWarehouseName(x.getWarehouseName());
            vo.setSapFactoryCode(x.getSapFactoryCode());
            vo.setWarehouseCode(x.getWarehouseCode());
            vo.setCode(x.getCode());
            vo.setGoodsId(x.getOuterItemId());
            vo.setGoodsName(x.getGoodsName());
            vo.setThirdExpiredQuantity(DomUtil.thousandthFormat2(x.getThirdExpiredQuantity(), isExcel));
            vo.setApproachExpiredQuantity(DomUtil.thousandthFormat2(x.getApproachExpiredQuantity(), isExcel));
            ecInventoryVOS.add(vo);
        });
        return Result.listSuccess(ecInventoryVOS, result.getTotal());
    }

    /**
     * ecLinkInventoryReport
     */
    @Override
    @FacadeInvoker
    public Result<List<EcLinkInventoryVO>> ecLinkInventoryReport(
        EcLinkInventoryReportRequest ecLinkInventoryReportRequest) {
        PageLinkDetailRequest request = new PageLinkDetailRequest();
        request.setDepartmentCodes(ecLinkInventoryReportRequest.getDepartmentCodes());
        request.setPlatformCodes(ecLinkInventoryReportRequest.getPlatformCodes());
        request.setSapFactoryCode(ecLinkInventoryReportRequest.getSapFactoryCode());
        request.setWarehouseCode(ecLinkInventoryReportRequest.getWarehouseCode());
        request.setCode(ecLinkInventoryReportRequest.getCode());
        request.setWarehouseIdList(ecLinkInventoryReportRequest.getWarehouseIdList());
        request.setGoodsIdList(ecLinkInventoryReportRequest.getGoodsIdList());
        request.setOuterItemIdList(ecLinkInventoryReportRequest.getOuterItemIdList());
        request.setCategoryIdList(ecLinkInventoryReportRequest.getCategoryIdList());
        request.setStart(ecLinkInventoryReportRequest.getStart());
        request.setLimit(ecLinkInventoryReportRequest.getLimit());
        request.setStatisticalDate(DomUtil.getToday());
        request.setOuterItemId(ecLinkInventoryReportRequest.getOuterItemId());
        log.info("pageQueryDetail_request={}", JSON.toJSONString(request));
        Result<List<EcInventoryDetail>> result = ecInventoryDetailService.pageLinkDetail(request);
        if (result == null || CollectionUtils.isEmpty(result.getResult())) {
            return Result.listEmptySuccess();
        }
        boolean isExcel = ecLinkInventoryReportRequest.getIsExcel();
        List<EcLinkInventoryVO> ecLinkInventoryVOS = new ArrayList<>();
        result.getResult().stream().forEach(x -> {
            EcLinkInventoryVO vo = new EcLinkInventoryVO();
            vo.setDepartmentName(x.getDepartmentName());
            vo.setPlatformName(x.getPlatformName());
            vo.setWarehouseName(x.getWarehouseName());
            vo.setWarehouseId(x.getWarehouseId());
            vo.setCode(x.getCode());
            vo.setSapFactoryCode(x.getSapFactoryCode());
            vo.setWarehouseCode(x.getWarehouseCode());
            vo.setGoodsId(x.getOuterItemId());
            vo.setGoodsName(x.getGoodsName());
            vo.setCategoryName(x.getCategoryName());
            vo.setDeliveryQuantity(DomUtil.numFormat2(x.getShipQunatity(), isExcel));
            vo.setAvailableQuantity(DomUtil.thousandthFormat2(x.getAvailableQuantity(), isExcel));
            vo.setOnwayQuantity(DomUtil.numFormat2(x.getNotArriveQuantity(), isExcel));//调拨未到货
            ecLinkInventoryVOS.add(vo);
        });
        return Result.listSuccess(ecLinkInventoryVOS, result.getTotal());
    }

    //获取人员ID
    private List<String> getEmpIds(String creator) {
        List<String> result = new ArrayList<>();
        if (StringUtils.isBlank(creator)) {
            return result;
        }
        JSONArray array = JSON.parseArray(creator);
        for (Object object : array) {
            JSONObject jsonObject = (JSONObject)JSONObject.toJSON(object);
            result.add(jsonObject.getString("empId"));
        }
        return result;
    }

    //获取业务人员ID
    private List<String> getDimensionIds(String creator) {
        List<String> result = new ArrayList<>();
        if (StringUtils.isBlank(creator)) {
            return result;
        }
        JSONArray array = JSON.parseArray(creator);
        for (Object object : array) {
            JSONObject jsonObject = (JSONObject)JSONObject.toJSON(object);
            if (StringUtils.isNotBlank(jsonObject.getString("empId"))) {
                result.add(jsonObject.getString("empId").substring(3));
            }
        }
        return result;
    }

    //找到归属业务单元，总部返回null
    private String findBizUnitId() {
        EmployeeGetCurrentLoginResponse response = bcOtsService.employeeGetCurrentLogin();
        log.info("EmployeeGetCurrentLoginResponse={}", JSON.toJSONString(response));
        String orgType = response.getRelatedOrganizationType();
        String orgId = response.getRelatedOrganizationId();
        int diff = orgType.compareTo(BRANCH_COMPANY_ORG_CODE);
        if (diff < 0) {
            return null;
        } else if (diff == 0) {
            return orgId;
        } else {
            GetTopOrganizationListRequest request = new GetTopOrganizationListRequest();
            Integer COMPANY_TYPE = Integer.valueOf(BRANCH_COMPANY_ORG_CODE);
            request.setId(orgId);
            request.setType(COMPANY_TYPE);
            Result<List<com.epoch.app.crplatformenhance.model.dto.TopOrganizationListResponse>> result
                = otsPlatformEnhanceService.getTopOrganizationList(request);
            List<TopOrganizationListResponse> responseList = result.getResult().stream().filter(
                x -> x.getType().equals(COMPANY_TYPE)).collect(Collectors.toList());
            return responseList.get(0).getId();
        }
    }
}
